package org.fnzn.service.Impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.fnzn.bean.*;
import org.fnzn.dao.*;
import org.fnzn.service.LrdRoleService;
import org.fnzn.service.UserRoleService;
import org.fnzn.tree.MenuTree;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.fnzn.bean.vo.User;
import org.fnzn.core.CommonConstant;
import org.fnzn.core.Constants;
import org.fnzn.core.Page;
import org.fnzn.core.Result;
import org.fnzn.service.base.AbstractService;
import org.fnzn.tree.AuthorityMenuTree;
import org.fnzn.util.CommonUtil;
import org.fnzn.util.DateTools;
import org.fnzn.util.DicReplace;
import org.fnzn.util.ResultGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.RequestBody;

@Service
public class LrdRoleServiceImpl extends AbstractService<LrdRole> implements LrdRoleService {

    @Autowired
    LrdOrgMapper lrdOrgMapper;
    @Autowired
    LrdRoleMapper lrdRoleMapper;
    @Autowired
    LrdRolefuncMapper lrdRolefuncMapper;
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    UserRoleService userRoleService;

    @Override
    public Result queryList(Map<String, Object> map) {
        // TODO Auto-generated method stub

        User user = CommonUtil.getUser();
        List<Map<String, Object>> userRole = user.getROLE_CD();
        String roleCd = "";
        for (Map<String, Object> map2 : userRole) {
            if (map2.get("ROLE_ID") != null && map2.get("ROLE_ID").toString().equals(Constants.ADMIN_ROLE)) {
                roleCd = Constants.ADMIN_ROLE;
            }
        }
        map.put("userId", user.getUser_id());
        map.put("orgCd", user.getOrgCD());
        Page page = new Page();
        if (map.get("limit") != null && map.get("page") != null) {
            page.setLimit(Integer.parseInt(map.get("limit").toString()));
            page.setPage(Integer.parseInt(map.get("page").toString()));
            PageHelper.startPage(page.getPage(), page.getLimit(), true);
        }
        LrdRole lrdRole = new LrdRole();
        if (!Constants.ADMIN_ROLE.equals(roleCd)) {
            lrdRole.setAdmin(false);
        }
        if (map.get("roleCd") != null && map.get("roleCd").toString().trim() != "") {
            lrdRole.setRoleCd(map.get("roleCd").toString());
        }
        if (map.get("roleFw") != null && map.get("roleFw").toString().trim() != "") {
            lrdRole.setRoleFw(map.get("roleFw").toString());
        }
        if (map.get("roleName") != null && map.get("roleName").toString().trim() != "") {
            lrdRole.setRoleName(map.get("roleName").toString());
        }
        List<Map<String, Object>> list = lrdRoleMapper.queryLrdRole(lrdRole);
        Map<String, String> dicMap = new HashMap<String, String>();
        dicMap.put("roleFw", "SYS_ORG_YYFW");
        DicReplace.replaceDic(list, dicMap);
        page.setRows(list);
        page.setTotal(new PageInfo<Map<String, Object>>(list).getTotal());
        return ResultGenerator.genSuccessResult(page);
    }

    @Override
    public Result InsertLrdRole(LrdRole lrdRole) {

        LrdRole role = findById(lrdRole.getRoleCd());
        if (role == null) {
            //获取当前登录用户的机构
            User user = CommonUtil.getUser();
            lrdRole.setRoleOrg(user.getOrgCD());
            int n = save(lrdRole);
            if (n > 0) {
                return ResultGenerator.genSuccessResult(lrdRole);
            } else {
                return ResultGenerator.genFailResult("添加失败");
            }
        } else {
            return ResultGenerator.genFailResult("添加失败,角色编号已存在");
        }

    }

    @Transactional
    @Override
    public Result updateLrdRole(LrdRole lrdRole) {
        lrdRole.setMtnDate(DateTools.getCurrentSysData(DateTools.SIMPLE_FORMAT));
        int n = update(lrdRole);
        if (n > 0) {
            return ResultGenerator.genSuccessResult(lrdRole);
        } else {
            return ResultGenerator.genFailResult("更新失败");
        }

    }

    @Override
    public Result deleteRole(String roleCd) {
        deleteById(roleCd);
        return ResultGenerator.genSuccessResult();
    }

    @Override
    @Transactional
    public void modifyAuthorityMenu(String roleCd, List<AuthorityMenuTree> menuTrees, String corpCd) {
        lrdRolefuncMapper.deleteByRoleCdAndResourceType(roleCd, CommonConstant.RESOURCE_TYPE_MENU);
        LrdRolefunc authority = null;
        for (AuthorityMenuTree menuTree : menuTrees) {
            authority = new LrdRolefunc(CommonConstant.RESOURCE_TYPE_MENU);
            authority.setCorpCd(corpCd);
            authority.setRoleCd(roleCd);
            authority.setFuncCd(menuTree.getId() + "");
            lrdRolefuncMapper.insertSelective(authority);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateAuthorityMenu(String roleCd, List<MenuTree> menuTrees) {
        lrdRolefuncMapper.deleteByRoleCdAndResourceType(roleCd, CommonConstant.RESOURCE_TYPE_MENU);
        lrdRolefuncMapper.deleteByRoleCdAndResourceType(roleCd, CommonConstant.RESOURCE_TYPE_BTN);
        List<Integer> integers = lrdRolefuncMapper.selectIdsByRoleCd(roleCd);
        for (MenuTree menus : menuTrees) {
            LrdRolefunc lrdRolefunc = new LrdRolefunc();
            lrdRolefunc.setFuncCd(String.valueOf(menus.getId()));
            lrdRolefunc.setResourceType(menus.getType());
            lrdRolefunc.setRoleCd(roleCd);
            lrdRolefunc.setCorpCd(CommonConstant.DEFAULT_CORP_CD);
            if (menus.getId() == 166) {
                System.out.println(menus);
            }
            lrdRolefuncMapper.insertSelective(lrdRolefunc);
        }
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public void modifyAuthorityElement(String roleCd, int menuId, int elementId, String corpCd) {
        LrdRolefunc authority = new LrdRolefunc(CommonConstant.RESOURCE_TYPE_BTN);
        authority.setCorpCd(corpCd);
        authority.setRoleCd(roleCd);
        authority.setFuncCd(elementId + "");
        if (lrdRolefuncMapper.selectByPrimaryKey(authority) == null) {
            lrdRolefuncMapper.insertSelective(authority);
        }
    }

    @Override
    public void removeAuthorityElement(String roleCd, int menuId, int elementId) {
        LrdRolefunc authority = new LrdRolefunc(CommonConstant.RESOURCE_TYPE_BTN);
        authority.setRoleCd(roleCd);
        authority.setFuncCd(elementId + "");
        lrdRolefuncMapper.delete(authority);
    }


    @Override
    public List<AuthorityMenuTree> getAuthorityMenu(String roleCd) {
        List<Menu> menus = menuMapper.selectMenuByAuthorityId(roleCd);
        List<AuthorityMenuTree> trees = new ArrayList<AuthorityMenuTree>();
        AuthorityMenuTree node = null;
        for (Menu menu : menus) {
            node = new AuthorityMenuTree();
            node.setText(menu.getTitle());
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return trees;
    }

    @Override
    public List<Integer> getAuthorityElement(String groupId) {
        LrdRolefunc authority = new LrdRolefunc(CommonConstant.RESOURCE_TYPE_BTN);
        authority.setRoleCd(groupId);
        List<LrdRolefunc> authorities = lrdRolefuncMapper.select(authority);
        List<Integer> ids = new ArrayList<Integer>();
        for (LrdRolefunc auth : authorities) {
            ids.add(Integer.parseInt(auth.getFuncCd()));
        }
        return ids;
    }

    @Override
    public List<LrdRole> selectAll() {
        return findAll();
    }

    /**
     * 根据当前登录用户id获取到下拉角色列表
     */
    @Override
    public Result getRole(String userId) {

        // 根据当前登录用户id获取到角色id
        LrdUserrole lrdUserrole = userRoleService.findBy("userId", userId);
        if (lrdUserrole.getRoleId().equals(Constants.ADMIN_ROLE)) {
            List<LrdRole> listRoles = findAll();
            return ResultGenerator.genSuccessResult(listRoles);
        }else{
            // 如果是销售经理登录，那么获取到的角色只有销售人员和项目经理
                List<LrdRole> list = lrdRoleMapper.getRole();
                return ResultGenerator.genSuccessResult(list);
        }
    }
}
